package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.CustomerService;
import com.atguigu.jxc.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gwk
 * @create 2021 -09 -05 0:07
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    CustomerDao customerDao;
    @Autowired
    LogService logService;
    @Override
    public Map<String, Object> list(Integer page, Integer rows, String customerName) {
        Map<String, Object> map = new HashMap<>();
        page = page == 0 ? 1 : page;
        int offSet = (page - 1)*rows;
        List<Goods> customerList = customerDao.list(offSet, rows, customerName);

        logService.save(new Log(Log.SELECT_ACTION,"客户列表分页名称模糊查询"));

        map.put("total",customerDao.getTotal(customerName));
        map.put("rows",customerList);
        return map;
    }

    @Override
    public ServiceVO save(Customer customer) {
        //客户ID是null,说明是新增，判断客户名字是否存在
        if (customer.getCustomerId() == null) {
            Customer exCustomerName = customerDao.findCustomerByName(customer.getCustomerName());
            if (exCustomerName != null) {
                return new ServiceVO(ErrorCode.ACCOUNT_EXIST_CODE, ErrorCode.ACCOUNT_EXIST_MESS);
            }
            customerDao.addCustomer(customer);
            logService.save(new Log(Log.INSERT_ACTION, "添加客户：" + customer.getCustomerName()));
        }else {
                customerDao.updateCustomer(customer);
                logService.save(new Log(Log.UPDATE_ACTION,"修改客户："+customer.getCustomerName()));
        }
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    @Override
    public ServiceVO delete(String ids) {
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        try {
            customerDao.delete(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ServiceVO(ErrorCode.CONSTRAINT_VIOLATION_CODE,ErrorCode.CONSTRAINT_VIOLATION_MESS);
        }
        logService.save(new Log(Log.DELETE_ACTION,"删除供应商"));
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);

    }
}
